﻿@using Compass.Wasm.Shared.Files
@inject HttpClient Http

<h3>测试上传单个文件</h3>
<InputFile class="form-control mb-2" OnChange="OnInputFileChange"/>

<p>图片类型</p>
<InputFile class="form-control mb-2" OnChange="OnInputFileChange" accept="image/*" />

<p>PDF类型</p>
<InputFile class="form-control mb-2" OnChange="OnInputFileChange" accept="application/pdf" />

<p>dwg,dxf类型</p>
<InputFile class="form-control mb-2" OnChange="OnInputFileChange" accept=".dwg,.dxf" />

<p>Excel,Word,PPT</p>
<InputFile class="form-control mb-2" OnChange="OnInputFileChange" accept=".xls,.xlsx,.xlsm" />
<InputFile class="form-control mb-2" OnChange="OnInputFileChange" accept=".doc,.docx" />
<InputFile class="form-control mb-2" OnChange="OnInputFileChange" accept=".ppt,.pptx" />




<p>@resultUri</p>
<p><a href="@resultUri" target="_blank">打开这个文件</a></p>
<p>给a标签添加download属性来下载文件</p>
<p><a href="@resultUri" download>下载这个文件</a></p>

<button class="btn btn-primary" disabled="@(!isUploaded)">上传完成才能按该按钮</button>

@code
{
    
    //微软官方文档，Blazor上传文件
    //https://learn.microsoft.com/zh-cn/aspnet/core/blazor/file-uploads?view=aspnetcore-6.0&pivots=webassembly

    private string resultUri;
    private bool isUploaded;

    private async Task OnInputFileChange(InputFileChangeEventArgs e)
    {   
        isUploaded=false;
    //e.GetMultipleFiles();//获取多个文件
        var file = e.File;//一个文件
        
        using var content = new MultipartFormDataContent();
        //允许上传最大100M的文件
        content.Add(content: new StreamContent(file.OpenReadStream(1024 * 1024*100)),
            name: "\"files\"", fileName: file.Name);
        try
        {
            var response = await Http.PostAsync("api/Uploader", content);
            var uploadResponse = await response.Content
                .ReadFromJsonAsync<UploadResponse>();
            
            resultUri = uploadResponse.RemoteUrl.ToString();
            isUploaded = true;
        }
        catch (Exception ex)
        {
            isUploaded = false;
            resultUri =$"上传文件异常：{ex}";
        }
    }

}
